package com.czh.framework.security.handler;

import com.alibaba.fastjson2.JSON;
import com.czh.common.constant.ResCode;
import com.czh.common.domain.AjaxRes;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthorizationFaultHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setContentType("application/json");
        ServletOutputStream outputStream = response.getOutputStream();
        AjaxRes fault = AjaxRes.fault("授权失败");
        fault.put(AjaxRes.CODE, ResCode.AUTHOR_FAULT);
        outputStream.write(JSON.toJSONBytes(fault));
        outputStream.close();
    }
}
